package scala.cookbook.akka

import akka.actor.{Actor, ActorSystem, Props}
import akka.util.Timeout

import scala.concurrent.Await
import scala.concurrent.duration._
import akka.pattern.ask

/**
  * Created by baiwf on 2017/5/13.
  */

case object AskNameMessage

class TestActor extends Actor {
  override def receive: Receive = {
    case AskNameMessage => sender() ! "Fred"
    case _ => println("unpected")
  }
}

object WaitActorReply extends App {
  val sys = ActorSystem("askname")
  val a = sys.actorOf(Props[TestActor], name = "my")
  implicit val timeout = Timeout(5 seconds)
  val future = a ? AskNameMessage
  val res = Await.result(future, timeout.duration).asInstanceOf[String]
  println(s"res=$res")

  val f2 = ask(a, AskNameMessage).mapTo[String]
  val res2 = Await.result(f2, 1 second)
  println(s"res2=$res2")

  sys.shutdown()
}
